"use client";
import {
  Box,
  Button,
  Flex,
  Grid,
  Input,
  InputGroup,
  InputRightAddon,
  InputRightElement,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Radio,
  RadioGroup,
  Slider,
  SliderFilledTrack,
  SliderThumb,
  SliderTrack,
} from "@chakra-ui/react";
import { motion } from "framer-motion";
import { useContext, useEffect, useState } from "react";
import { MainContext } from "@/src/providers/MainProvider";
import { MacroProfile, MacroAction } from "@/src/types/types";
import EditItem from "../base/EditItem";
import MacroActionList from "../base/MacroActionList";
import { addMacroActionList, getMacroBytes } from "@/src/libs/macro";
import MouseComponent from "../Common/MouseComponent";

function Macro() {
  const [startRecord, setStartRecord] = useState(false);
  const [delayTime, setDelayTime] = useState(10);
  const [delayType, setDelayType] = useState("1");
  const [cycles, setCycles] = useState(10);
  const [cycleType, setCycleType] = useState("0");
  const [selectAction, setSelectAction] = useState(-1);

  const {
    macroProfiles,
    setMacroProfiles,
    currentSelectMacroProfile,
    setCurrentSelectMacroProfile,
    connectedMouse,
    t,
  } = useContext(MainContext);

  const [macroActionList, setMarcoActionList] = useState<MacroAction[]>([]);

  useEffect(() => {
    if (macroProfiles.length > currentSelectMacroProfile) {
      setMarcoActionList(macroProfiles[currentSelectMacroProfile].list);
    }
  }, [currentSelectMacroProfile, macroProfiles]);

  useEffect(() => {
    console.log("macroProfiles", macroProfiles);
    const macroBytes = getMacroBytes(macroProfiles);
    console.log("macroBytes", macroBytes);
    connectedMouse?.setMacroData(macroBytes);
  }, [macroProfiles]);

  useEffect(() => {
    const addAction = (event: KeyboardEvent | MouseEvent) => {
      event.preventDefault();
      if (event instanceof KeyboardEvent) {
        if (event.repeat) {
          return;
        }
        setMarcoActionList((actionList: MacroAction[]) => {
          const time = Math.floor(event.timeStamp);
          const delay =
            delayType == "0" ? 0 : delayType == "1" ? -1 : delayTime;
          return addMacroActionList(actionList, event, time, delay);
        });
      } else {
        if (event.target instanceof HTMLButtonElement) {
          if (event.target?.classList?.contains("btn-record")) return;
        }
        setMarcoActionList((actionList: MacroAction[]) => {
          const time = Math.floor(event.timeStamp);
          const delay =
            delayType == "0" ? 0 : delayType == "1" ? -1 : delayTime;
          return addMacroActionList(actionList, event, time, delay);
        });
      }
    };
    window.oncontextmenu = (e) => {
      e.preventDefault();
    };
    if (startRecord) {
      window.document.addEventListener("keydown", addAction);
      window.document.addEventListener("keyup", addAction);
      window.document.addEventListener("mousedown", addAction);
      window.document.addEventListener("mouseup", addAction);
    } else {
      window.document.removeEventListener("keydown", addAction);
      window.document.removeEventListener("keyup", addAction);
      window.document.removeEventListener("mousedown", addAction);
      window.document.removeEventListener("mouseup", addAction);
    }

    return () => {
      window.document.removeEventListener("keydown", addAction);
      window.document.removeEventListener("keyup", addAction);
      window.document.removeEventListener("mousedown", addAction);
      window.document.removeEventListener("mouseup", addAction);
    };
  }, [startRecord]);

  const addMacro = () => {
    setMacroProfiles([
      ...macroProfiles,
      { name: t("530") + (macroProfiles.length + 1), type: "0", list: [] },
    ]);
    setCurrentSelectMacroProfile(macroProfiles.length);
  };
  const changeProfileName = (index: number, name: string) => {
    setMacroProfiles((macroProfiles: MacroProfile[]) => {
      return macroProfiles.map((profile, i) =>
        index == i ? { ...profile, name: name } : profile
      );
    });
  };

  const deleteProfile = (index: number) => {
    setCurrentSelectMacroProfile(
      Math.min(currentSelectMacroProfile, macroProfiles.length)
    );
    setMacroProfiles((macroProfiles: MacroProfile[]) => {
      return macroProfiles.filter((m, i) => i !== index);
    });
  };
  const startRec = () => {
    setStartRecord(!startRecord);
    if (!startRecord) {
      setMarcoActionList([]);
    } else {
      setMacroProfiles((macroProfiles: MacroProfile[]) => {
        return macroProfiles.map((macro, index) => {
          return index == currentSelectMacroProfile
            ? { ...macro, list: macroActionList }
            : macro;
        });
      });
    }
    return false;
  };

  useEffect(() => {
    if (macroProfiles.length) {
      localStorage.setItem("mouse_macro", JSON.stringify(macroProfiles));
    }
  }, [macroProfiles]);

  useEffect(() => {
    const initMacro = async () => {
      const data = await localStorage.getItem("mouse_macro");
      if (data) {
        const macroArr = JSON.parse(data);
        setMacroProfiles(macroArr);
        if (macroArr[0]) {
          setCurrentSelectMacroProfile(0);
        }
      }
    };
    initMacro();
  }, []);

  const deleteActionList = () => {
    setMarcoActionList((actionList: MacroAction[]) => {
      return actionList.filter((m, i) => i !== selectAction);
    });
  };

  return (
    <Flex w={"100%"} gap={"0.5rem"} position={"relative"}>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.3, delay: 0.1, timeConstant: "ease-out" }}
      >
        <Box className="panel-main-bg" h={"max-content"}>
          <Flex
            alignItems={"center"}
            w={"100%"}
            className="panel-main-fg px-4 gap-1"
          >
            <Box>
              <svg
                className="w-5"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="27537"
                width="48"
                height="48"
              >
                <path
                  d="M896 768v128h-85.333333v-128h-85.333334v-85.333333h256v85.333333h-85.333333zM213.333333 768v128H128v-128H42.666667v-85.333333h256v85.333333H213.333333z m256-512V128h85.333334v128h85.333333v85.333333H384V256h85.333333z m0 170.666667h85.333334v469.333333h-85.333334V426.666667z m-341.333333 170.666666V128h85.333333v469.333333H128z m682.666667 0V128h85.333333v469.333333h-85.333333z"
                  p-id="27538"
                  fill="#e6e6e6"
                ></path>
              </svg>
            </Box>
            <Box className="font-medium w-64">{t("500")}</Box>
          </Flex>
          <Box>
            <Box className="macro-list p-2 rounded">
              <ul className="h-[400px] panel-main-fg overflow-auto">
                {macroProfiles.map((macro, index) => (
                  <li
                    key={index}
                    data-selected={index == currentSelectMacroProfile}
                    className="flex justify-between items-center hover:cursor-pointer"
                    onClick={() => setCurrentSelectMacroProfile(index)}
                  >
                    <EditItem
                      name={macro.name}
                      onChange={(value: string) => {
                        changeProfileName(index, value);
                      }}
                      onDelete={() => deleteProfile(index)}
                    />
                  </li>
                ))}
              </ul>
              <Grid
                templateColumns={"1fr 1fr 1fr"}
                gap={"0.5rem"}
                className="py-2"
                justifyContent={"center"}
              >
                <Button
                  className="main-btn"
                  variant={"unstyled"}
                  onClick={() => addMacro()}
                >
                  {t("501")}
                </Button>
              </Grid>
            </Box>
          </Box>
        </Box>
      </motion.div>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.3, delay: 0.2, timeConstant: "ease-out" }}
      >
        <Box
          as={motion.div}
          initial={{ opacity: 0, scale: 1.05 }}
          animate={{ opacity: 1, scale: 1 }}
          className="panel-main-bg"
          h={"max-content"}
        >
          <Flex
            alignItems={"center"}
            w={"100%"}
            className="panel-main-fg px-4 gap-1"
          >
            <Box>
              <svg
                className="w-5"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="27537"
                width="48"
                height="48"
              >
                <path
                  d="M896 768v128h-85.333333v-128h-85.333334v-85.333333h256v85.333333h-85.333333zM213.333333 768v128H128v-128H42.666667v-85.333333h256v85.333333H213.333333z m256-512V128h85.333334v128h85.333333v85.333333H384V256h85.333333z m0 170.666667h85.333334v469.333333h-85.333334V426.666667z m-341.333333 170.666666V128h85.333333v469.333333H128z m682.666667 0V128h85.333333v469.333333h-85.333333z"
                  p-id="27538"
                  fill="#e6e6e6"
                ></path>
              </svg>
            </Box>
            <Box className="font-medium w-80">{t("510")}</Box>
          </Flex>
          <Box className="p-2">
            <MacroActionList
              list={macroActionList}
              onChange={setMarcoActionList}
            />
          </Box>
        </Box>
      </motion.div>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.3, delay: 0.4, timeConstant: "ease-out" }}
      >
        <Box as={motion.div} className="panel-main-bg" w={"20rem"}>
          <Box className="p-2">
            <Button
              w={"100%"}
              className="main-btn btn-record !text-white"
              _focusVisible={{ boxShadow: "none" }}
              onClick={() => startRec()}
            >
              {startRecord ? t("520") : t("521")}
            </Button>
          </Box>
          <Box className="px-2 pb-2 flex flex-col gap-2">
            <Box className="p-3 panel-main-fg">
              <Box className="pb-3">{t("511")}</Box>
              <RadioGroup
                defaultValue={delayType}
                onChange={(value) => setDelayType(value)}
              >
                <Flex flexDirection={"column"} rowGap={"0.8rem"}>
                  <Radio value="0">{t("512")}</Radio>
                  <Radio value="1">{t("513")}</Radio>
                  <Flex alignItems={"center"} justifyContent={"space-between"}>
                    <Radio value="2">{t("514")}</Radio>
                    <InputGroup w={"5rem"}>
                      <Input
                        defaultValue={delayTime}
                        onChange={(event) => {
                          setDelayTime(parseInt(event?.target.value));
                        }}
                        w={"auto"}
                        h={"2rem"}
                        variant={"unstyled"}
                        className="!bg-[#184FB652] !rounded-none !pl-3"
                      />
                      <InputRightElement>
                        <Box className="h-8">ms</Box>
                      </InputRightElement>
                    </InputGroup>
                  </Flex>
                </Flex>
              </RadioGroup>
            </Box>
          </Box>
        </Box>
      </motion.div>
      <Box className="absolute top-0 left-1/3 w-2/3 h-full -z-10">
        <MouseComponent />
      </Box>
    </Flex>
  );
}

export default Macro;
